<template>
  <el-card
    class="flex enterpriseKnowledge h-full"
    :loading="loading"
    style="width: calc(100% - 10px); margin-left: 10px; height: 100%"
  >
    <div style="display: inline-flex" class="w-full h-full">
      <div class="aside">
        <el-row class="w-full" justify="space-between" style="padding: 10px 0; align-items: center">
          <el-col :span="14" style="font-size: 14px">企业知识库</el-col>
          <el-col :span="10">
            <el-button type="primary" text @click="addClass">添加分类</el-button>
          </el-col>
        </el-row>

        <div
          v-for="(item, index) in classHostList"
          :key="index"
          :class="activeClass.name == item.name ? 'item active-item' : 'item'"
        >
          <div class="item-name" @click="clickClass(item)">{{ item.name }}</div>
          <el-popover
            placement="bottom"
            trigger="hover"
            popper-style="display: inline-flex"
            v-if="index !== 0"
          >
            <template #reference>
              <svg-icon iconClass="icon_more" />
            </template>
            <el-button type="primary" text @click="handleHotClassEdit(item)">编辑</el-button>
            <el-button type="primary" text @click="handleHotClassDelete(item)">删除</el-button>
          </el-popover>
        </div>
      </div>
      <div style="height: 100%; flex: 1; border-left: 1px solid rgba(0, 0, 0, 0.0901960784)">
        <div style="padding: 20px" v-if="activeClass">
          <div class="toolbar" style="display: flex; flex-wrap: wrap">
            <el-form class="w-full inline-flex" style="display: inline-flex">
              <el-form-item label="关键词">
                <el-input
                  v-model="searchKeyword"
                  placeholder="输入搜索关键词"
                  clearable
                  @keyup.enter="getQuestionByUserId"
                  style="width: 140px; margin-right: 10px"
                >
                </el-input>
              </el-form-item>
              <!-- <el-form-item label="时间范围">
                <el-date-picker
                  v-model="timeRange"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item> -->
              <el-form-item label="状态">
                <el-select
                  v-model="enabled"
                  placeholder="状态"
                  clearable
                  style="width: 80px; margin-left: 10px"
                >
                  <el-option label="正常" :value="true"></el-option>
                  <el-option label="停用" :value="false"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="getQuestionByUserId" type="primary" style="margin-left: 10px"
                  >查询</el-button
                >
              </el-form-item>
            </el-form>

            <!-- <el-button @click="importData">导入数据</el-button> -->
            <!-- <el-button @click="exportData">导出数据</el-button> -->
          </div>

          <el-button type="primary" @click="addQuestion" style="margin: 10px 0">添加问题</el-button>

          <el-table :data="filteredQuestions" style="width: calc(100% - 100px)" height="420">
            <el-table-column prop="question" label="标准问题" width="180"></el-table-column>
            <el-table-column prop="enabled" label="当前状态" width="100">
              <template #default="scope">
                {{ scope.row.enabled ? "正常" : "停用" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="updated"
              label="操作时间"
              width="180"
              v-if="activeClass.name == '全部分类'"
            >
              <template #default="scope">
                <div>{{ fotmatDay(scope.row.updated) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" @click="editQuestion(scope.row)">编辑</el-button>
                <el-button type="text" @click="toggleStatus(scope.row)">
                  {{ scope.row.enabled ? "停用" : "启用" }}
                </el-button>
                <el-button type="text" @click="deleteQuestion(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalQuestions"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="limit"
            v-model:current-page="page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增 | 编辑分类 -->
    <el-dialog :title="classDialogTitle" v-model="classDialogVisible" width="30%">
      <el-form
        :model="classDetailItem"
        ref="formRef"
        label-width="120px"
        label-position="top"
        :rules="rules"
      >
        <el-form-item label="分类名字" prop="name">
          <el-input
            v-model="classDetailItem.name"
            type="text"
            @keyup.enter="handleSubmitClassName"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="classDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitClassName">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="questionTitle" v-model="questionVisbile" width="70%">
      <el-form
        :model="questionForm"
        ref="questionRef"
        label-width="120px"
        label-position="top"
        :rules="questionFormRules"
      >
        <el-form-item label="标准问题" prop="question">
          <el-input v-model="questionForm.question" placeholder="输入内容" />
        </el-form-item>
        <el-form-item label="相似问法" prop="similarQuestions">
          <el-input v-model="questionForm.similarQuestions" placeholder="输入相似问法" />
        </el-form-item>
        <el-form-item label="默认回答" prop="answer">
          <el-input type="textarea" v-model="questionForm.answer" placeholder="输入内容" />
        </el-form-item>
        <el-form-item label="选择分类" prop="cid">
          <el-select v-model="questionForm.cid" placeholder="选择选项">
            <el-option
              v-for="item in allClassList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="questionVisbile = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitQuestion">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { USER_MODEL } from "@/constants/index";
import storage from "@/utils/localforage/index";

import { ElMessage } from "element-plus";
import {
  knowledgeBaseSetStatus,
  knowledgeBaseDelete,
  knowledgeBaseAddorupdate,
  knowledgeBaseAnsewer,
  knowledgeBaseDdetail,
  knowledgeBaseHotTableData,
  knowledgeBaseTableData,
  knowledgeBaseSearch,
  knowledgeBaseUnidentified,
  addknowledgeBaseClassification,
  knowledgeBaseClassificationHotList,
  knowledgeBaseClassificationList,
  updateKnowledgeBaseClassification,
} from "@/api/node-admin-api/class.js";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";
import dayjs from "dayjs";

const classHostList = ref([]);
const filteredQuestions = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const enabled = ref("");
const page = ref(1);
const limit = ref(10);
const totalQuestions = ref(0);

onMounted(() => {
  getHotClassList();
});

// 获取热门分类列表
const getHotClassList = () => {
  loading.value = true;
  knowledgeBaseClassificationHotList({ limit: 999 })
    .then((res) => {
      if (res.code == 20000) {
        classHostList.value = [{ name: "全部分类" }, ...res.data.records];
        clickClass(classHostList.value[0]);
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 获取全部分类
const allClassList = ref([]);
loading.value = true;
const getAllClassList = () => {
  knowledgeBaseClassificationList({ page: page.value, limit: limit.value })
    .then((res) => {
      if (res.code == 20000) {
        allClassList.value = res.data.records;
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const classDetailItem = ref({ name: "" });
const classDialogTitle = ref("");
const classDialogVisible = ref(false);
// 添加热门分类
const addClass = (item) => {
  classDialogVisible.value = true;
  classDialogTitle.value = "添加分类";
  classDetailItem.value = { name: "" };
};

const activeClass = ref("");
// 根据分类检索问题
const clickClass = (item) => {
  activeClass.value = item;
  searchKeyword.value = "";
  enabled.value = "";
  getAllClassList();
  if (item.name == "全部分类") {
    getQuestionByUserId();
  } else {
    getQuestionByClassId(item);
  }
};
// 获取这个用户全部分类的问题
const getQuestionByUserId = () => {
  loading.value = true;
  const userInfo = storage.get(USER_MODEL);
  const params = {
    userId: userInfo.user.userId,
    keyword: searchKeyword.value,
    enabled: enabled.value,
    page: page.value,
    limit: limit.value,
    cid: activeClass.value.id ? activeClass.value.id : "",
  };
  knowledgeBaseTableData(params)
    .then((res) => {
      if (res.code == 20000) {
        filteredQuestions.value = res.data.records;
        totalQuestions.value = res.data.total;
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 根据热门分类检索问题
const timeRange = ref([]);
const getQuestionByClassId = (item) => {
  loading.value = true;
  const params = {
    cid: item.cid,
    page: page.value,
    limit: limit.value,
    startDate: timeRange.value.length ? timeRange.value[0] : "",
    endDate: timeRange.value.length ? timeRange.value[1] : "",
  };
  knowledgeBaseHotTableData(params)
    .then((res) => {
      if (res.code == 20000) {
        filteredQuestions.value = res.data.records;
        totalQuestions.value = res.data.total;
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 编辑热门分类
const handleHotClassDelete = (item) => {};

// 编辑热门分类
const handleHotClassEdit = (item) => {
  classDialogVisible.value = true;
  classDialogTitle.value = "编辑分类";
  classDetailItem.value = { ...item };
};

const handleSubmitClassName = () => {
  if (!classDetailItem.value.name) {
    errorMessage("请输入分类名字！");
    return;
  }
  loading.value = true;

  if (classDialogTitle.value == "编辑分类") {
    const prams = {
      ...classDetailItem.value,
      id: classDetailItem.value.cid,
      name: classDetailItem.value.name,
      isDelete: false,
    };
    updateKnowledgeBaseClassification(prams)
      .then((res) => {
        if (res.code == 20000) {
          successMessage("编辑分类成功！");
          classDialogVisible.value = false;
          getHotClassList();
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        loading.value = false;
      });
  } else {
    addknowledgeBaseClassification({ name: classDetailItem.value.name })
      .then((res) => {
        if (res.code == 20000) {
          successMessage("新增分类成功！");
          classDialogVisible.value = false;
          getHotClassList();
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        loading.value = false;
      });
  }
};

const fotmatDay = (val) => {
  return dayjs(new Date(val)).format("YYYY-MM-DD HH:mm:ss");
};

// 删除热门分类
const handleHotClassDeleet = (item) => {
  loading.value = true;
  const prams = {
    ...classDetailItem.value,
    isDelete: true,
  };
  successMessage("删除分类成功！还没有接口");

  // updateKnowledgeBaseClassification(prams)
  //   .then((res) => {
  //     if (res.code == 20000) {
  //       classDialogVisible.value = false;
  //       getHotClassList();
  //     }
  //   })
  //   .catch((e) => {
  //     errorMessage(e.message);
  //   })
  //   .finally((res) => {
  //     loading.value = false;
  //   });
};

const questionTitle = ref("");
const questionVisbile = ref(false);
const questionForm = ref({
  question: "",
  similarQuestions: "",
  answer: "",
  cid: "",
});

const questionFormRules = ref({
  question: [{ required: true, message: "请输入标准问题", trigger: "blur" }],
  answer: [{ required: true, message: "请输入默认回答", trigger: "blur" }],
  cid: [{ required: true, message: "请选择分类", trigger: "change" }],
});

const categoryOptions = [
  { value: "category1", label: "分类1" },
  { value: "category2", label: "分类2" },
  { value: "category3", label: "分类3" },
];

const questionRef = ref(null);
const handleSubmitQuestion = () => {
  loading.value = true;
  questionRef.value.validate((valid) => {
    if (valid) {
      const params = {
        id: 0,
        ...questionForm.value,
        similarQuestions: [questionForm.value.similarQuestions],
      };
      knowledgeBaseAddorupdate(params)
        .then((res) => {
          if (res.code == 20000) {
            console.log("res:", res);
            if (activeClass.value == "全部分类") {
              getQuestionByUserId();
            } else {
              getQuestionByClassId(activeClass.value);
            }
          }
        })
        .catch((e) => {
          console.log("handleSubmitQuestion: ", e);
          errorMessage(e.message);
        })
        .finally((res) => {
          loading.value = false;
          questionVisbile.value = false;
        });
    } else {
      console.log("表单验证失败");
      return false;
    }
  });
};

const addQuestion = () => {
  getAllClassList();
  questionTitle.value = "添加问题";
  questionForm.value = {
    question: "",
    similarQuestions: "",
    answer: "",
    cid: "",
    id: 0,
  };
  questionVisbile.value = true;
};

const editQuestion = (row) => {
  getAllClassList();
  knowledgeBaseDdetail({ qid: row.id }).then((res) => {
    if (res.code == 20000) {
      questionTitle.value = `编辑问题: ${row.question}`;
      questionForm.value = {
        ...row,
        ...res.data.detail,
        similarQuestions: res.data.detail.similarQuestions
          ? res.data.detail.similarQuestions[0]
          : "",
      };
      questionVisbile.value = true;
    }
  });
};

const importData = () => {
  successMessage("导入数据功能");
};

const exportData = () => {
  successMessage("导出数据功能");
};

// 更新状态
const toggleStatus = (row) => {
  const params = {
    id: row.id,
    enabled: row.enabled ? false : true,
  };
  loading.value = true;
  knowledgeBaseSetStatus(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`状态已更新!`);
        if (activeClass.value.name == "全部分类") {
          getQuestionByUserId();
        } else {
          getQuestionByClassId();
        }
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 删除知识库
const deleteQuestion = (row) => {
  const params = {
    id: row.id,
  };
  loading.value = true;
  knowledgeBaseDelete(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`问题已删除!`);
        if (activeClass.value.name == "全部分类") {
          getQuestionByUserId();
        } else {
          getQuestionByClassId();
        }
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const handleSizeChange = (page) => {
  page.value = page;
  getQuestionByUserId();
};

const handleCurrentChange = (newSize) => {
  limit.value = newSize;
  getQuestionByUserId();
};

const handleQueueCurrentChange = (newPage) => {
  page.value = newPage;
  if (activeClass.value.name == "全部分类") {
    getQuestionByUserId();
  } else {
    getQuestionByClassId();
  }
};

const resetSearch = () => {
  page.value = 1;
  limit.value = 10;
  searchKeyword.value = "";
  timeRange.value = [];
  enabled.value = null;
  if (activeClass.value.name == "全部分类") {
    getQuestionByUserId();
  } else {
    getQuestionByClassId();
  }
};
</script>

<style lang="scss" scoped>
:deep(.enterpriseKnowledge .el-card__body) {
  display: inline-flex;
  width: 100%;
  height: 100%;
}

.aside {
  width: 180px;
  min-width: 180px;
  height: 100%;
  padding: 3px 8px 8px;

  .item {
    height: 48px;
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: space-between;
    border: 1px solid #00000017;
    border-bottom: 0;
    border-right: 0;
    border-left: 0;

    font-size: var(--el-menu-item-font-size);
    height: var(--el-menu-item-height);
    line-height: var(--el-menu-item-height);

    cursor: pointer;

    .item-name {
      width: calc(100% - 20px);
      height: 100%;
    }
  }

  .active-item {
    color: var(--el-menu-active-color);
  }
}
:deep(.el-card__body) {
  width: 100%;
}
</style>
